import {
  reqGetCollections,
  reqGetAsks
} from '../../utils/api.js'

import {
  getReqData,
  getErrorMsg
} from '../../utils/util.js'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    arr: [],
    openType: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    
    const {
      data: openType
    } = options
    
    wx.setNavigationBarTitle({
      title: 'collection' === openType ? '已收藏的文章' : '已咨询的问题',
    })
    
    // 如果没有userinfo那么就退出，不发送信息
    if (null === app.globalData.userInfo) {
      this.setData({
        arr: []
      })
      return null;
    }
    
    const {
      result
    } = 'collection' === openType ? await reqGetCollections() : await reqGetAsks()

    const data = getReqData(result)

    if (!data) {
      console.error(getErrorMsg(result))
      return null
    }    

    this.setData({
      arr: data.list,
      openType
    })
  },

  /**
   * 下拉到最低，再获取数据。
   */
  onLower: async function (e) {
    wx.showLoading({
      title: '请稍后...',
    })

    let {
      activeIndex,
      arr,
      tabs
    } = this.data
    const skipCount = arr[activeIndex].length
    const cName = tabs[activeIndex]
    const result = await reqExamples({
      listCount,
      skipCount,
      cName
    })
    const temp = getReqData(result)
    // console.log('下拉返回的数据', temp)

    if (!temp || temp.length <= 0) {
      setTimeout(() => {
        wx.hideLoading()
      }, 1000)
      return null
    };

    arr[activeIndex] = arr[activeIndex].concat(temp)

    this.setData({
      arr
    })

    setTimeout(() => {
      wx.hideLoading()
    }, 1000)
  }
})